// This is JDefenceTower, a simple tower defence style game
//
// Copyright (C) 2010 Maximilian Junker
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation; either version 3 of the License, or (at your option) any later
// version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, see <http://www.gnu.org/licenses/>.

package junker.defence.model;

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class PeriodicCreateBehaviour extends Behaviour {
	// Duration of a tick in nano seconds
	public static final long	TICK_DUR	= 10 * 1000 * 1000;
	
	private CreationPattern	pattern;
	private Map				map;

	public PeriodicCreateBehaviour(CreationPattern pattern, Map map) {
		super();
		this.pattern = pattern;
		this.map = map;
	}

	@Override
	protected List<GameRequest> execute(StepSummary s, TimeSpan span) {
		MapObjectDescription d;
		List<GameRequest> events = new LinkedList<GameRequest>();
		for(long t : calculateTicks(span)){
			if ((d = pattern.get(t)) != null) {
				events.add((GameRequest) new CreateRequest(this, map, d, this
						.getMapObject().getLocation(),t*TICK_DUR));
			} 
		}
		return events;
	}

	@Override
	public void conflict(GameRequest e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void commit(GameRequest e) {
		// TODO Auto-generated method stub

	}
	
	private  long[] calculateTicks(TimeSpan span) {
		long[]	ticks;
		long startTick = (span.getStart() / TICK_DUR);
		long endTick = (span.getEnd() / TICK_DUR)-1;

		// Converting to int should be ok, unless it is a really really long
		// frame (Integer.MAX_INT * 10ms)
		int tick_count = (int) (endTick - startTick) + 1;
		ticks = new long[tick_count];
		for (int i = 0; i < tick_count; i++) {
			ticks[i] = startTick + i;
		}
		return ticks;
	}

}
